package com.lanling.eduservice.controller;


import com.alibaba.excel.util.StringUtils;
import com.lanling.eduservice.client.OrdersClient;
import com.lanling.eduservice.entity.EduVideo;
import com.lanling.eduservice.orther.R;
import com.lanling.eduservice.orther.ZhenhuaException;
import com.lanling.eduservice.client.VodClient;
import com.lanling.eduservice.service.EduVideoService;
import com.lanling.eduservice.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author 胡振华
 * @since 2020-11-10
 */
@RestController
@RequestMapping("/eduservice/edu-video")
@CrossOrigin
public class EduVideoController {

    @Autowired
    private EduVideoService eduVideoService;

    //注入vodClient
    @Autowired
    private VodClient vodClient;

    @Autowired
    private OrdersClient ordersClient;

    //添加小节
    @PostMapping("addVideo")
    public R addVideo(@RequestBody EduVideo video){
        boolean flag = eduVideoService.save(video);
        if (flag){
            return R.ok();
        }else {
            return R.error();
        }

    }

    //根据id查询小节信息
    @GetMapping("getVideoById/{videoId}")
    public R getVideoById(@PathVariable String videoId, HttpServletRequest request){
        EduVideo eduVideo = eduVideoService.getById(videoId);
        String memberIdByJwtToken = JwtUtils.getMemberIdByJwtToken(request.getHeader("usertoken"));
        boolean isbuy = false;
        if (!org.springframework.util.StringUtils.isEmpty(memberIdByJwtToken)){
            isbuy = ordersClient.isBuyCourse(eduVideo.getCourseId(), memberIdByJwtToken);
            System.out.println(isbuy+"-----------------------------------");
        }

        return R.ok().data("eduVideo",eduVideo).data("isbuy",isbuy);
    }

    //修改小节
    @PostMapping("updateVideo")
    public R updateVideo(@RequestBody EduVideo eduVideo){
        boolean flag = eduVideoService.updateById(eduVideo);
        if (flag){
            return R.ok();
        }else {
            return R.error();
        }
    }

    //删除小节
    @DeleteMapping("deleteVideo/{id}")
    public R deleteVideo(@PathVariable String id){
        //根据小节id获取视频id，调用方法实现视频删除
        EduVideo eduVideo = eduVideoService.getById(id);
        String videoSourceId = eduVideo.getVideoSourceId();
        //判断小节里面是否有视频id
        if(!StringUtils.isEmpty(videoSourceId)) {
            //根据视频id，远程调用实现视频删除
            R result = vodClient.removeAlyVideo(videoSourceId);
            if(result.getCode() == 20001) {
                throw new ZhenhuaException(20001,"删除视频失败，熔断器...");
            }
        }
        //删除小节
        eduVideoService.removeById(id);
        return R.ok();
    }

}

